/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.onlylemi.mapview.slice;

import com.onlylemi.mapview.ResourceTable;
import com.onlylemi.mapview.ToastUtil;
import com.onlylemi.mapview.library.MapView;
import com.onlylemi.mapview.library.MapViewListener;
import com.onlylemi.mapview.library.layer.LocationLayer;
import com.onlylemi.mapview.library.utils.MapUtils;
import com.onlylemi.mapview.menu.MenuDialog;
import com.onlylemi.mapview.menu.MenuProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.utils.Point;
import ohos.agp.window.dialog.ToastDialog;
import ohos.media.image.PixelMap;
import ohos.sensor.agent.CategoryOrientationAgent;
import ohos.sensor.bean.CategoryOrientation;
import ohos.sensor.data.CategoryOrientationData;
import ohos.sensor.listener.ICategoryOrientationDataCallback;

import java.util.ArrayList;
import java.util.List;

public class LocationLayerTestSlice extends AbilitySlice implements Component.ClickedListener {

    private MapView mapView;
    private LocationLayer locationLayer;

    private boolean openSensor = false;

    private static final long INTERVAL = 100000000L;
    private CategoryOrientationAgent categoryOrientationAgent = new CategoryOrientationAgent();
    private ICategoryOrientationDataCallback orientationDataCallback;
    private CategoryOrientation orientationSensor;

    private List<String> itemList;

    private Runnable runnable;
    float degree;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_location_layer_test);

        Text tvTitle = (Text) findComponentById(ResourceTable.Id_tv_title);
        tvTitle.setText("LocationLayerTest");
        Image ivMenu = (Image) findComponentById(ResourceTable.Id_iv_more);
        ivMenu.setVisibility(Component.VISIBLE);
        ivMenu.setClickedListener(this);

        itemList = new ArrayList<>();
        itemList.add("Close Compass");
        itemList.add("Set Compass CircleRotate");
        itemList.add("Set Compass ArrowRotate");
        itemList.add("Open Sensor");

        mapView = (MapView) findComponentById(ResourceTable.Id_mapview);
        PixelMap bitmap = MapUtils.getPixelMap(this, ResourceTable.Media_map);
        mapView.loadMap(bitmap);
        mapView.setMapViewListener(new MapViewListener() {
            @Override
            public void onMapLoadSuccess() {
                locationLayer = new LocationLayer(mapView, new Point(400, 400));
                locationLayer.setOpenCompass(true);
                locationLayer.setCompassIndicatorCircleRotateDegree(60);
                locationLayer.setCompassIndicatorArrowRotateDegree(-30);
                mapView.addLayer(locationLayer);
                mapView.refresh();
            }

            @Override
            public void onMapLoadFail() {
            }
        });

        runnable = new Runnable() {
            @Override
            public void run() {
                locationLayer.setCompassIndicatorCircleRotateDegree(-degree);
                locationLayer.setCompassIndicatorArrowRotateDegree(mapView.getCurrentRotateDegrees()
                        + degree);
                mapView.refresh();
            }
        };

        // 创建传感器回调对象。
        orientationDataCallback = new ICategoryOrientationDataCallback() {
            @Override
            public void onSensorDataModified(CategoryOrientationData categoryOrientationData) {
                // 对接收的categoryOrientationData传感器数据对象解析和使用
                if (mapView.isMapLoadFinish() && openSensor) {
                    degree = categoryOrientationData.getValues()[0];
                    getUITaskDispatcher().asyncDispatch(runnable);
                }
            }

            @Override
            public void onAccuracyDataModified(CategoryOrientation categoryOrientation, int index) {
                // 使用变化的精度
            }

            @Override
            public void onCommandCompleted(CategoryOrientation categoryOrientation) {
                // 传感器执行命令回调
            }
        };
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_iv_more:
                MenuDialog.with(this)
                        .load(itemList)
                        .setListener(new MenuDialog.OnItemClickListener() {
                            @Override
                            public void onItemClick(MenuProvider adapter, int position) {
                                switch (position) {
                                    case 0:
                                        if (locationLayer.isOpenCompass()) {
                                            itemList.set(position, "Open Compass");
                                        } else {
                                            itemList.set(position, "Close Compass");
                                        }
                                        adapter.notifyDataSetItemChanged(position);
                                        locationLayer.setOpenCompass(!locationLayer.isOpenCompass());
                                        mapView.refresh();
                                        break;
                                    case 1:
                                        float rotate = 90;
                                        locationLayer.setCompassIndicatorCircleRotateDegree(rotate);
                                        mapView.refresh();
                                        ToastUtil.show("circle rotate: " + rotate);
                                        break;
                                    case 2:
                                        rotate = 30;
                                        locationLayer.setCompassIndicatorArrowRotateDegree(rotate);
                                        mapView.refresh();
                                        ToastUtil.show("arrow rotate: " + rotate);
                                        break;
                                    case 3:
                                        if (openSensor) {
                                            itemList.set(position, "Open Sensor");

                                            // 取消订阅传感器数据
                                            if (orientationSensor != null) {
                                                categoryOrientationAgent.releaseSensorDataCallback(
                                                        orientationDataCallback, orientationSensor);
                                            }
                                        } else {
                                            itemList.set(position, "Close Sensor");

                                            // 获取传感器对象，并订阅传感器数据
                                            orientationSensor = categoryOrientationAgent.getSingleSensor(
                                                    CategoryOrientation.SENSOR_TYPE_ORIENTATION);
                                            if (orientationSensor != null) {
                                                categoryOrientationAgent.setSensorDataCallback(
                                                        orientationDataCallback, orientationSensor, INTERVAL);
                                            }
                                        }
                                        openSensor = !openSensor;
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }).showDialog();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        // 取消订阅传感器数据
        if (orientationSensor != null) {
            categoryOrientationAgent.releaseSensorDataCallback(
                    orientationDataCallback, orientationSensor);
        }
    }
}
